package com.py.custom.business.demo.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.py.custom.business.demo.core.mapstruct.BeanConvertUtils;
import com.py.custom.business.demo.core.service.StudentService;
import com.py.custom.business.demo.core.service.model.StudentDTO;
import com.py.custom.business.demo.protocol.groups.StudentGroup;
import com.py.custom.business.demo.protocol.request.StudentRequest;
import com.py.custom.data.entity.demo.Student;
import com.py.custom.data.mapper.demo.StudentDao;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import java.util.List;
import java.util.Objects;

/**
 * description：
 */
@Service
@Validated
@Slf4j
public class StudentServiceImpl extends ServiceImpl<StudentDao, Student> implements StudentService {

    /**
     * 对象转换类
     */
    @Autowired
    private BeanConvertUtils beanConvertUtils;

    /**
     * mybatis-plus增强的数据访问类
     */
    @Autowired
    private StudentDao studentDao;

    /**
     * 查询学生集合，@Validated 指定分组校验： 参数/返回值
     *
     * @param studentRequest 参数
     * @return 返回值
     */
    @Override
    @Validated(value = StudentGroup.DefaultGroup.class)
    public List<StudentDTO> getStudentList(StudentRequest studentRequest) {
        // 查询条件
        QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(Objects.nonNull(studentRequest.getId()), "id", studentRequest.getSex())
                .eq(!StringUtils.isEmpty(studentRequest.getName()), "name", studentRequest.getName())
                .eq(!StringUtils.isEmpty(studentRequest.getSex()), "sex", studentRequest.getSex());

        // 分页
        Page<Student> page = new Page<>(studentRequest.getPageNum(), studentRequest.getPageSize());

        // 查询
        Page<Student> studentPage = studentDao.selectPage(page, queryWrapper);

        List<Student> studentList = studentPage.getRecords();
        // 转换
        return beanConvertUtils.student2DtoList(studentList);
    }

    @Override
    @Validated(value = StudentGroup.SaveGroup.class)
    @Transactional(rollbackFor = Exception.class)
    public boolean saveStudent(StudentRequest studentRequest) {
        // 保存学生
        Student student = beanConvertUtils.studentReqCon(studentRequest);
        studentDao.insert(student);
        // 写入操作日志
        Student logStu = new Student();
        logStu.setName("日志");
        studentDao.insert(logStu);
        return true;
    }
}
